<template>
	<section>
		<el-dialog v-if="dialogVisible" :title="title" v-model="dialogVisible" width="1400px" :before-close="handleClose">
			<el-form inline ref="form" :model="formData" :rules="formRules" label-width="140px">
				<el-form-item label="单据号">
					<el-input disabled v-model="formData.recoveryCode" class="w-300"></el-input>
				</el-form-item>
				<el-form-item label="回收单位" prop="purchaseUnityId" label-width="140px">
					<el-select @change="changepurchaseUnity" class="w-300" placeholder="---请输入回收单位名称---" v-model="formData.purchaseUnityId">
						<el-option v-for="item in optionsPurchaseUnity" :key="item.purchaseUnityId"
							:label="item.purchaseUnityName" :value="item.purchaseUnityId" />
					</el-select>
				</el-form-item>
				<el-form-item label="回收时间" prop="recoveryTime" label-width="80px">
					<el-date-picker style="width: 300px" v-model="formData.recoveryTime" value-format="YYYY-MM-DD" format="YYYY-MM-DD"/>
				</el-form-item>
				<el-form-item label="回收方式" prop="recoveryType" label-width="140px">
					<el-select placeholder="---请选择回收方式---" v-model="formData.recoveryType"  class="w-300">
						<el-option v-for="item in optionsState" :key="item.value" :label="item.label"
							:value="item.value" class="w-300" />
					</el-select>
				</el-form-item>
				<el-form-item  :rules="{required:formData.recoveryType==2?true:false,message:'请选择期望上门回收时间',trigger:'change'}" label="期望上门回收时间" prop="expectedDate" 
				label-width="140px">
					<el-date-picker style="width: 300px" v-model="formData.expectedDate" value-format="YYYY-MM-DD" format="YYYY-MM-DD"/>
				</el-form-item>
				<!-- <el-form-item :rules="{required:formData.recoveryType==1?true:false,message:'请选择物流',trigger:'change'}" label="物流" prop="logisticsId">
					<el-select placeholder="---请选择物流---" v-model="formData.logisticsId"  class="w-300">
						<el-option v-for="item in logList" :key="item.logisticsId" :label="item.logisticsName"
							:value="item.logisticsId" />
					</el-select>
				</el-form-item>
				<el-form-item :rules="{required:formData.recoveryType==1?true:false,message:'请输入物流单号',trigger:'blur'}" label="物流单号" prop="logisticsNum">
					<el-input v-model="formData.logisticsNum" class="w-300"></el-input>
				</el-form-item> -->
				<el-row style="margin-bottom: 10px;">
					<!-- <div style="margin-right: 20px;height: 32px;line-height: 32px;">回收空瓶</div>	  -->
					<el-button @click="addMaterial()">新增空瓶</el-button>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label-width="120px">
							<el-table :data="itemsData" border style="width: 1360px">
								<el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
								<el-table-column label="空瓶编码" min-width="120">
									<template #default="scope">{{ scope.row.materialCode }}</template>
								</el-table-column>
								<el-table-column label="空瓶名称" min-width="230">
									<template #default="scope">{{ scope.row.materialName }}</template>
								</el-table-column>
								<el-table-column label="空瓶规格" min-width="230">
									<template #default="scope">{{ scope.row.materialSpecs }}</template>
								</el-table-column>
								<el-table-column label="单价" min-width="100">
									<template #default="scope">
										<span >{{ scope.row.recoverPrice }}</span>
									</template>
								</el-table-column>
								<el-table-column label="供应商" min-width="200" prop="materialItemId">
									<template #default="scope">
										<el-select placeholder="---请选择供应商---" v-model="scope.row.recoverySuplyId" style="width: 100%" @change="onSupplierChange(scope.row)">
											<el-option v-for="item in scope.row.emptiesSupplierList" :key="item.supplierId" :label="item.supplierName" :value="item.supplierId" />
										</el-select>
									</template>
								</el-table-column>
								<el-table-column label="标识码" min-width="150">
									<template #default="scope">
						               <el-input v-model="scope.row.materialBarCode" style="width: 100%" ></el-input>
					                </template>
								</el-table-column>
								<el-table-column label="回收数量" min-width="100">
									<template #default="scope">
						               <el-input-number v-model="scope.row.recoveryCount" @change="handleChange(scope.row)" style="width: 100%" :step="1" :min="0" controls-position="right"></el-input-number>
					                </template>
								</el-table-column>
								<el-table-column label="金额" min-width="100">
									<template #default="scope">
										<el-input disabled v-model="scope.row.recoverPriceTotal" style="width: 100%" ></el-input>
					                </template>
								</el-table-column>
								<!-- <el-table-column label="物流" min-width="150">
									<template #default="scope">
										<el-select :rules="{required:formData.recoveryType==1?true:false,message:'请选择物流',trigger:'change'}" style="width: 100%;" v-model="scope.row.logisticsId"  class="w-300">
											<el-option v-for="item in logList" :key="item.logisticsId" :label="item.logisticsName"
												:value="item.logisticsId" />
										</el-select>
									</template>
								</el-table-column>
								<el-table-column label="物流单号" min-width="100">
									<template #default="scope">
								       <el-input :rules="{required:formData.recoveryType==1?true:false,message:'请输入物流单号',trigger:'blur'}" v-model="scope.row.logisticsNum" style="width: 100%" ></el-input>
								    </template>
								</el-table-column> -->
								<el-table-column label="备注" min-width="150" prop="remark">
									<template #default="scope">
										<el-input v-model="scope.row.remark"/>
									</template>
								</el-table-column>
								<el-table-column label="文本备注" min-width="160">
                                	<template #default="scope">
										<div style="color: #318cf2;text-decoration: underline;cursor: pointer;" @click="onShowNotes(scope.row.notes)">查看内容</div>
									</template>
								</el-table-column>
								<el-table-column label="空瓶照片" min-width="150">
								<template #default="scope">
                                        <sc-upload-multiple 
											:disabled="mode=='Show'"
                                            v-model="scope.row.recoveryImages"
                                            :objName="'Supply/RevoceryOrder'" 
                                            :uploadType="'OSS'" 
                                            :bucketName="'jtmc'" 
                                            :limit="5"
                                           
                                             />
                                </template>
							</el-table-column>
								<el-table-column label="操作" min-width="100">
									<template #default="scope">
										<el-button size="small" @click="deleteRow(scope.$index, scope.row)">删除</el-button>
									</template>
								</el-table-column>
							</el-table>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<span slot="footer" class="">
				<div class="dialog-footer">
					<el-button style="width: 80px;" size="large" @click="Close">取消</el-button>
					<el-button style="width: 80px;" size="large" type="primary" @click="handleSubmit">保存</el-button>
				</div>
			</span>
		</el-dialog>

		<!-- 选择物料-空瓶 -->
		<template>
			<el-dialog v-model="materialState" title="选择空瓶" :width="1200" :center="true" destroy-on-close append-to-body>
				<sc-empties-choice :queryList="formData" ref="scMaterialChoice" ></sc-empties-choice>
				<template #footer >
					<br>
					<el-button @click="materialState = false">取 消</el-button>
					<el-button type="primary" :loading="isSaveing" @click="setMaterialChoice">确定</el-button>
				</template>
			</el-dialog>
		</template>
		 <!-- 查看文本备注 -->
		 <template>
            <el-dialog v-model="notesDialog" title="文本备注" :width="500" :center="true" append-to-body style="height: 480px">
                <el-row>
                    <div v-html="materialNotes" style="width: 100%"></div>
                </el-row>
                <template #footer>
                    <el-button @click="notesDialog = false">关 闭</el-button>
                </template>
            </el-dialog>
        </template>
	</section>

</template>

<script>
import tool from "@/utils/tool";
export default {
	props: {
		title: String // 弹框标题
	},
	data() {
		return {
			dialogVisible: false,
			materialState: false,
			formData: {},
			itemsData:[],
			formRules: {
				purchaseUnityId: [{
					required: true,
					message: '请选择回收单位名称',
					trigger: 'change'
				}],
				recoveryTime: [{
					required: true,
					message: '请选择回收时间',
					trigger: 'change'
				}],
				recoveryType: [{
					required: true,
					message: '请选择回收方式',
					trigger: 'change'
				}],
				// logisticsId: [{
				// 	required: true,
				// 	message: '请选择物流',
				// 	trigger: 'change'
				// }],
				// logisticsNum: [{
				// 	required: true,
				// 	message: '请输入物流单号',
				// 	trigger: 'blur'
				// }]
			},
			optionsState: [],
			optionsPurchaseUnity: [],
			logList: [],
			kpList: [],
			upplierList: [],
			notesDialog:false,
            materialNotes:"",
		};
	},
	mounted() {
		this.orgType = tool.data.get("USER_INFO").AccountType;
	},
	methods: {
		// 页面初始化
		openDialog(modalData) {
			console.log('modalData：', modalData);
			this.dialogVisible = true;
		    this.initOptions(); // 初始话字典数据
			if(modalData) (this.formData = modalData, this.itemsData = modalData.recoveryOrderItems)
			console.log('formData', this.formData)
			console.log('this.formData.itemsData', this.itemsData)
		},
		changepurchaseUnity(){
			this.itemsData = [];
		},
		// 添加空瓶
		handleSubmit() {
			for (const item of this.itemsData) {
                if (!item.recoverySuplyId) {
					this.$message.error('请选择供应商');
                    return;
                }
				// if (!item.materialBarCode) {
				// 	this.$message.error('请输入标识码');
    //                 return;
    //             }
				if (!item.recoveryCount) {
					this.$message.error('请输入回收数量');
                    return;
                }
				// if (!item.remark) {
				// 	this.$message.error('请输入备注');
    //                 return;
    //             }
            }
			this.formData.recoveryOrderItems = this.itemsData
			this.$refs.form.validate(valid => {
				if (valid) {
					this.handleFormSubmit()
				} else {
					console.log('表单验证失败');
					return false;
				}
			});
		},
		 //新增&编辑回收空瓶
		async handleFormSubmit() {
			// console.log('提交的数据:', this.formData);
            let url = '';
			// 特殊业务 this.title === '新增回收空瓶' ? url = 'recovery-order/create' :  url = 'recovery-order/update'
	        this.title === '新增回收空瓶' ? url = 'recovery-order/create' :  url = 'recovery-order/create'
            const returnValue = await this.$API.auth.PostProcessApi.post(url, this.formData);
            if (returnValue.status === 200) {
              this.$message.success('操作成功');
			  this.clearView()
			  this.dialogVisible = false;
			  this.$emit('success');
            } else {
              this.$message.error(`操作失败: ${returnValue.msg}`);
            }
        },
		// 从空瓶列表中选中数据返回
		setMaterialChoice() {
			let materials = JSON.parse(JSON.stringify(this.$refs.scMaterialChoice.selectionRows)) // 大型数据结构，频繁使用,可能会导致性能问题
			console.log(materials);
			materials.forEach(element => {
				element.recoverySuplyId = null
				element.recoveryCount = 0
				element.recoverPriceTotal = 0
			});
			this.itemsData = [...this.itemsData,...materials] // 特殊业务可以重复添加
			this.$refs.scMaterialChoice.clearSelectionFun();
			this.materialState = false;
		},
		deleteRow(index,row) {
			 this.itemsData.splice(index, 1);
		},
		clearView(){
			this.formData = {} // this.$refs.form.resetFields();
			this.itemsData = []
		},
		Close() {
			this.clearView()
			this.dialogVisible = false
		},
		handleClose(done) {
			this.clearView()
			done();
		},
		addMaterial() {
			if (!this.formData.purchaseUnityId) {
				this.$message.error('请选择回收单位');
			}else{
				this.materialState = true;
				this.$nextTick(() => {
					this.$refs.scMaterialChoice.initMaterialType('23', false); //空瓶
				})
			}

		},
		async initOptions() {
			//获取空瓶名称
			try {
				const returnName = await this.$API.auth.PostProcessApi.post("recovery-order/getmaterialpages");
				if (returnName.status == 200) {
					this.kpList = returnName.response
				} else {
					this.$message.error("操作失败:" + returnName.msg);
				}
			} catch (error) { }

            //获取回收单位
			try {
				const returnStatus = await this.$API.auth.GetProcessApi.get(
					"store/current-purchaseUnity"
				);
				if (returnStatus.status == 200) {
					this.optionsPurchaseUnity = returnStatus.response;
					this.formData.pId = this.optionsPurchaseUnity[0].purchaseUnityId;
				} else {
					this.$message.error("操作失败:" + returnStatus.msg);
				}
			} catch (error) {  }

			//获取回收方式
			try {
				const returnType = await this.$API.auth.PostProcessApi.post( "base-dictionary/options", { Codes: ["RecoveryType"] }
				);
				if (returnType.status == 200) {
					this.optionsState = returnType.response.find((p) => p.code == "RecoveryType" ).optionsDetails;
				} else {
					this.$message.error("操作失败:" + returnType.msg);
				}
			} catch (error) { }


			//获取物流公司
			try {
				const returnCom = await this.$API.auth.PostProcessApi.post(
					"logistics/pages",
				);
				if (returnCom.status == 200) {
					this.logList = returnCom.response.data
				} else {
					this.$message.error("操作失败:" + returnCom.msg);
				}
			} catch (error) { }

			//获取酒商
			// try {
			// 	const returnValue = await this.$API.auth.PostProcessApi.post( "recovery-order/getstoresupplierlist",
			// 	);
			// 	if (returnValue.status == 200) {
			// 		this.upplierList = returnValue.response
			// 	} else {
			// 		this.$message.error("操作失败" + returnValue.msg);
			// 	}
			// } catch (error) { }

		},
		handleChange(row) {
		   this.mulFunction(row.recoverPrice,row.recoveryCount)
		   row.recoverPriceTotal = this.mulFunction(row.recoverPrice,row.recoveryCount)
        },
		//乘法精度丢失 移动到utils 工具类中
        mulFunction (arg1, arg2) {
           var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
           try { m += s1.split(".")[1].length } catch (e) { }
           try { m += s2.split(".")[1].length } catch (e) { }
           return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
        },
		//供应商变化
		onSupplierChange(row){
			var supplierInfo=row.emptiesSupplierList.filter((item)=>item.supplierId==row.recoverySuplyId)[0];
			row.recoverPrice=supplierInfo.recoverPrice;
			//this.mulFunction(row.recoverPrice,row.recoveryCount)
		    row.recoverPriceTotal = this.mulFunction(row.recoverPrice,row.recoveryCount);
		},
		//显示文本备注
        onShowNotes(notes){
            console.log("显示文本备注",notes)
            this.notesDialog=true;
            this.materialNotes=notes;
        }
	}
};
</script>

<style scoped>
.dialog-footer {
	text-align: center;
}
.w-300{
	width: 300px;
}
/deep/ .el-upload--picture-card{
    width: 50px;
    height: 50px;
}
/deep/ .el-upload{
    width: 50px;
    height: 50px;
    line-height: 50px;
}
/deep/ .el-upload-list--picture-card .el-upload-list__item{
    width: 50px;
    height: 50px;
    line-height: 50px;
}
/deep/ .el-upload-list--picture-card .el-upload-list__item-thumbnail{
    width: 50px;
    height: 50px;
    line-height: 50px;
}
</style>
